<?php

declare(strict_types=1);
/**
 * 创建人 : Forpastime
 *
 * @link     http://hypercmf.com
 * @document https://hyperf.wiki
 * @contact  forpastime@qq.com
 * @git  https://gitee.com/hypercmf/hypercmf1.0.git
 */
namespace App\Middleware\Auth;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;

class AdminTokenMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var HttpResponse
     */
    protected $response;

    /**
     * @var HttpRequest
     */

    protected $request;

    /**
     * AdminTokenMiddleware constructor.
     * @param HttpResponse $response 注意这里的response 是 ResponseInterface 是hyperf
     * @param RequestInterface $request 注意这里的request 是 RequestInterface  是hyperf
     */
    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->request = $request;
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $token = $request->getHeader('token');

        if (! empty($token[0])) {
            // 接口鉴权
            $info = explode('_',$token[0]);
            $redis = ApplicationContext::getContainer()->get(Redis::class);
            if(!$redis->get('HyperCMF:admin_token:'.$info[0]) || $redis->get('HyperCMF:admin_token:'.$info[0]) != $info[1]){
                return $this->response->json(
                    [
                        'code' => -1,
                        'data' => [],
                        'msg' => 'Token验证失败！请重新登录获取Token',
                    ]
                );
            }
            return $handler->handle($request);
        }else{
            return $this->response->json(
                [
                    'code' => -1,
                    'data' => [],
                    'msg' => 'Token缺失无法验证！',
                ]
            );
        }

    }
}